package yagwl.client.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * DTO nodes in a tree
 */
@SuppressWarnings("serial")
public class TreeNodeDTO extends ItemDTO implements Serializable {

  private static final Logger log = Logger.getLogger(TreeNodeDTO.class
      .getName());
  private TreeNodeDTO parent;
  private List<TreeNodeDTO> children;
  private List<ItemDTO> items;
  //private boolean open;

  public TreeNodeDTO getParent() {
    return parent;
  }

  public void setParent(TreeNodeDTO parent) {
    this.parent = parent;
  }

  public void addChild(TreeNodeDTO treeNode) {
    if (children == null)
      children = new ArrayList<TreeNodeDTO>();
    children.add(treeNode);
  }

  public void setChildren(List<TreeNodeDTO> children) {
    this.children = children;
  }

  public List<TreeNodeDTO> getChildren() {
    return children;
  }

  public void setItems(List<ItemDTO> items) {
    this.items = items;
  }

  public List<ItemDTO> getItems() {
    return items;
  }

  //public void setOpen(boolean open) {
  //  this.open = open;
  //}

  //public boolean isOpen() {
  //  return open;
  //}

  /**
   * prints ancestors and descendants that has been loaded in memory
   */
  public void printTree() {
    log.finer("TreeNode.printTree: " + this.getClass().getName());
    log.finer("Ancestors");
    printAncestor(this.parent);
    log.finer("Descendants");
    printDescendant(this);
  }

  private void printAncestor(TreeNodeDTO node) {
    if (node == null)
      return;
    printAncestor(node.getParent());
    printNode(node);
  }

  private void printDescendant(TreeNodeDTO node) {
    if (node == null)
      return;
    printNode(node);
    if (node.getChildren() != null)
      for (TreeNodeDTO child : node.getChildren())
        printDescendant(child);
  }

  private void printNode(TreeNodeDTO node) {
    String children = "";
    String products = "";
    if (node.getChildren() != null)
      for (TreeNodeDTO child : node.getChildren())
        children = children + child.getLabel() + ",";
    if (node.getItems() != null)
      for (ItemDTO item : node.getItems())
        products = products + item.getLabel() + ",";
    log.finer(node.getLabel() + " <" + children + "> <" + products + ">");
  }

}
